package com.asm.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class LengthFieldBasedFrameDecoderTestClient {
    public static void main(String[] args) throws InterruptedException {
        Channel ch = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_SNDBUF, 6)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                    }
                })
                .connect("localhost", 8080)
                .sync()
                .channel();

        Scanner scanner = new Scanner(System.in);
        // 测试拆包
//        while (true) {
//            String s = scanner.nextLine();
//            ByteBuf buf = ch.pipeline().firstContext().alloc().buffer();
//            buf.writeInt(18);
//            buf.writeBytes(new byte[]{1,2,3,4,5,6,7,8,9,1,2,3,4,5});
//            ch.writeAndFlush(buf);
//            System.out.println("==>");
//        }
        // 测试粘包
        byte[] bytes = new byte[100];
        for (int i = 0; i < 100; i++) {
            bytes[i] = (byte)i;
        }
        while (true) {
            String s = scanner.nextLine();
            ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
            buf.writeInt(80);
            buf.writeBytes(bytes);
//            buf.writeInt(2);
//            buf.writeBytes(new byte[]{3,4});
            ch.writeAndFlush(buf);
            System.out.println("==>");
        }
    }

}
